from flask import views, render_template, request, url_for, \
    redirect, Blueprint, make_response
from flask_jwt_extended import create_access_token
from flask import jsonify
from flask import request
from flask_jwt_extended import jwt_required, get_jwt_identity
import json
from result_code import Code
from models import User
from result import Result


login = Blueprint('login', __name__)


class LoginView(views.MethodView):
    def get(self):
        return render_template('login.html')

    def post(self):
        username = request.json.get("username")
        password = request.json.get("pwd")
        # print(username, password)
        user = User.query.filter(User.username == username).first()
        # print(f"usrname: {username}, pwd: {password}")
        if user is None or password != user.pwd:
            return vars(Result(msg="用户名或密码错误"))

        user_dic = vars(user)
        del user_dic['_sa_instance_state']
        token = create_access_token(identity=username)
        # The return type must be a string, dict, list, tuple with headers or status
        resp = vars(Result(Code.TOKEN_OK.value, user_dic, "密码正确", token))
        print(resp)
        return resp


@login.route('/logout')
def logout():
    resp = make_response("del success")
    resp.delete_cookie("username")
    return resp


@login.route('/verify', methods=["GET"])
@jwt_required(optional=True)  # 如果不带参数，用户没带有效token，会返回401
def verify():
    current_user = get_jwt_identity()  # 将token转换为原来的username
    dic = {'username': current_user}
    if current_user:
        return vars(Result(Code.TOKEN_OK.value, dic, "token is ok"))
    else:
        return vars(Result(Code.TOKEN_ERROR.value, None, "token are failed"))

